﻿import DeviceCardList from "@/views/business/devices/components/DeviceCardList.vue";
import DeviceAPI from "@/api/business/device.api";
import { forEach } from "lodash-es";
import { store } from "@/store";
import deviceApi from "@/api/business/device.api";

export const useDevicesStore = defineStore("devices", () => {
  const activeDeviceCardList = ref<CardItem[]>([]);
  // 启用设备列表
  let activeDeviceList: DeviceConfig[] = [];
  const deviceTypeAndModes = useStorage<KeyValueItem[]>("deviceTypeAndModes", [] as KeyValueItem[]);

  onMounted(() => {
    loadActiveDevices();
  });

  // 加载设备列表
  function loadActiveDevices() {
    DeviceAPI.getDevices(undefined, true).then((res) => {
      activeDeviceCardList.value.length = 0;

      activeDeviceList = res;
      forEach(res, (item) => {
        activeDeviceCardList.value.push({
          id: item.id,
          title: item.deviceName,
          stationNum: item.stationNum,
          deviceType: item.deviceType,
          connected: false,
          props: [],
        });
      });
      console.log("✅ ActiveDeviceCardList Loaded", activeDeviceCardList.value);

      DeviceAPI.getAllDeviceConnectStatus().then((dataArr) => {
        forEach(dataArr, (kvItem) => {
          const existItem = activeDeviceCardList.value.find((item2) => item2.id === kvItem.key);
          if (existItem) {
            existItem.connected = kvItem.value;
          }
        });
      });
    });
  }

  // 保存设备并刷新启用设备列表
  async function saveDeviceAndRefresh(deviceConfig: DeviceConfig) {
    return deviceApi.modifyDeviceConfig(deviceConfig).then(() => {
      // 更新成功后，重新加载设备
      loadActiveDevices();
    });
  }

  // 加载设备类型和型号
  function loadDeviceTypeAndModes() {
    DeviceAPI.getDeviceTypeAndModes().then((res) => {
      deviceTypeAndModes.value = res;
    });
  }

  return {
    activeDeviceCardList,
    activeDeviceList,
    loadActiveDevices,
    deviceTypeAndModes,
    loadDeviceTypeAndModes,
    saveDeviceAndRefresh,
  };
});

export function useDevicesStoreHook() {
  return useDevicesStore(store);
}
